#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

import cv2
import numpy as np


def getFilteredImg(img):
    FILTER_MIN = np.array([50, 39, 40], np.uint8)
    FILTER_MAX = np.array([110, 76, 76], np.uint8)
    frame_threshed = cv2.inRange(img, FILTER_MIN, FILTER_MAX)
    # frame_threshed2 = cv2.cvtColor(frame_threshed, cv2.COLOR_HSV2BGR)
    result = cv2.bitwise_or(img, img, mask=frame_threshed)
    return result


def check(locs):
    bodyRatio = float(locs[0][2]) / float(locs[0][3])
    headRatio = float(locs[1][2]) / float(locs[1][3])
    bodyMiddle = int(locs[0][0] + locs[0][2] / 2)
    headMiddle = int(locs[1][0] + locs[1][2] / 2)
    print("# bodyRatio: {}".format(bodyRatio))
    print("# headRatio: {}".format(headRatio))
    print("# bodyMiddle: {}".format(bodyMiddle))
    print("# headMiddle: {}".format(headMiddle))
    if (bodyRatio > 0.5 or bodyRatio < 0.6) and (headRatio > 0.9 or headRatio < 1.1) and (
                abs(bodyMiddle - headMiddle) < 5):
        return True
    else:
        return False


def debugPositionDetect(img, contours):
    temp = img.copy()
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        # leftmost = tuple(cnt[cnt[:, :, 0].argmin()][0])
        # rightmost = tuple(cnt[cnt[:, :, 0].argmax()][0])
        # temp = cv2.circle(temp, leftmost, 1, (255, 255, 0), -1)
        # temp = cv2.circle(temp, rightmost, 1, (255, 255, 0), -1)
        temp = cv2.rectangle(temp, (x, y), (x + w, y + h), (0, 255, 0), 1)
    return temp


def getPosition(path):
    img = cv2.imread(path)
    img = getFilteredImg(img)
    ret, thresh = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 1, 255, 0)
    _, contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    contourLocs = sorted(
        list(map(lambda cnt: cv2.boundingRect(cnt)
                 # + tuple([cnt[cnt[:, :, 0].argmin()][0]])
                 # + tuple([cnt[cnt[:, :, 0].argmax()][0]])
                 , contours)),
        key=lambda x: x[2] * x[3],
        reverse=True)[
                  0:2]

    print("# contours.len: {}".format(len(contours)))
    print("# contourLocs: {}".format(contourLocs))

    debugImg = debugPositionDetect(img, contours)
    cv2.imwrite(path.replace(".png", "_detect_debug.png"), debugImg)

    if check(contourLocs):
        print("# check(contourLocs) sucess")
        x = int(
            (contourLocs[0][0] + float(contourLocs[0][2] / 2) + contourLocs[1][0] + float(contourLocs[1][2] / 2)) / 2)
        y = int(contourLocs[1][1] + float(contourLocs[0][1] - contourLocs[1][1]) * 0.9)
        print("# x: {} , y: {}".format(x, y))
        return tuple([x, y])
    else:
        print("# check(contourLocs) fail")

        raise Exception("check(contourLocs) fail")


if __name__ == '__main__':
    print(getPosition('images/00000_1514972261.png'))
    sys.exit(0)
